<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '用户名不能为空' },
          {
            pattern: /^[a-z0-9]{4,10}$/i,
            message: '用户名只能数字字母组成长度4到10位',
            trigger: 'onChange',
          },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          {
            pattern: /^[a-z0-9]{6,10}$/i,
            message: '密码只能数字字母组成长度6到10位',
            trigger: 'onChange',
          },
          {
            validator: checkPwd,
            message: '两次输入的密码不一致',
            trigger: 'onChange',
          },
        ]"
      />
      <van-field
        v-model="password2"
        type="password"
        name="password2"
        label="确认密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          {
            pattern: /^[a-z0-9]{6,10}$/i,
            message: '密码只能数字字母组成长度6到10位',
            trigger: 'onChange',
          },
          {
            validator: checkPwd,
            message: '两次输入的密码不一致',
            trigger: 'onChange',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userRegister, userQuery } from "@/model/userModel.js";


export default {
  data() {
    return {
      username: "", //用户名
      password: "", //密码
      password2: "", //确认密码
    };
  },
  methods: {
    checkPwd() {
      return this.password == this.password2;
    },
    async onSubmit(values) {
      //检查用户名是否存在
      let res2 = await userQuery({
        username: values.username,
      });
      if(res2.data.length){
        this.$toast.fail('该用户名已经存在');
        return false;
      }

      await userRegister({
        username: values.username,
        password: values.password,
      });
      
      this.$emit("changeActive",0);
    },
  },
};
</script>

<style></style>
